package com.zhuojy.equity.mall.admin.web.controller;


import com.zhuojy.equity.mall.admin.common.constant.Constants;
import com.google.code.kaptcha.Producer;
import com.zhuojy.equity.mall.admin.web.config.RuoYiConfig;

import com.zhuojy.equity.mall.admin.common.support.Result;
import com.zhuojy.equity.mall.admin.manager.cache.RedisManager;
import com.zhuojy.equity.mall.admin.service.dto.res.CaptchaResDTO;
import org.springframework.beans.factory.annotation.Autowired;
import com.zhuojy.equity.mall.admin.common.utils.Base64;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zhuojy.equity.mall.admin.common.utils.IdUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

import java.util.concurrent.TimeUnit;

@RestController
public class CaptchaController{

    @Autowired
    private  RedisManager redisManager;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;
    /**
     * 生成图形验证码
     * @param:null
     * @return:Ajax_Result（统一返回工具）
     *
     */
    @GetMapping("/captchaImage")
    public Result<CaptchaResDTO> getCode(HttpServletResponse response )throws IOException{

        CaptchaResDTO captchaResDTO = new CaptchaResDTO();
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        System.out.println(verifyKey);
        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();

        String capText = captchaProducerMath.createText();
        capStr = capText.substring(0, capText.lastIndexOf("@"));
        code = capText.substring(capText.lastIndexOf("@") + 1);
        image = captchaProducerMath.createImage(capStr);
        System.out.println(code);
        boolean b = redisManager.insertObject(code,verifyKey, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        if(b){
            // 转换流信息写出
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            try
            {
                ImageIO.write(image, "jpg", os);
            }
            catch (IOException e)
            {
                return new Result<>(e.getMessage());
            }
            String base64 = Base64.encode(os.toByteArray());
            captchaResDTO.setUuid(uuid);
            captchaResDTO.setImg(base64);
            return new Result<>(captchaResDTO);
        }
        else {
           return null;
        }
    }


}